from __future__ import with_statement
import eeml, time, sys, logging, credentials
import simplejson as json
import common

# parameters
API_KEY = credentials.pachube_key()
#API_URL = '/api/6001.xml'
API_URL = '/api/9081.xml'
READING_FILE = '/var/www/readings.json'
#READING_FILE = 'readings.json'

common.setup_logging()
run = True
eeml_readings = [eeml.Data(0,0)]*25 # 1 voltage reading + 24 watt readings

while run:
    with open(READING_FILE, 'r') as f:
        l = f.read().encode()
    try:
        readings = json.loads(l)
    except:
        logging.debug('json failure: '+"'"+l+"'")
        readings = {u'datetime': ''}

    # print readings
    pac = eeml.Pachube(API_URL, API_KEY)
    # pac.update([eeml.Data(0, int(readings[14],16), unit=eeml.Celsius()), eeml.Data(1, readings[10], unit=eeml.RH())])
    if readings[u'datetime'] != '':
        # reading = int(readings[u'mA'])
        raw = readings[u'raw'][7:] # we won't actually reference raw[0]
        volts = round(readings[u'volts'],2)
        # print volts
        # watts1 = round(readings[u'watts1'],2)
        # watts2 = round(readings[u'watts2'],2)
        eeml_readings[0] = eeml.Data(0,volts)
        for i in range(1,25):
            amps = common.to_amps(i, raw[i])
            eeml_readings[i] = eeml.Data(i,amps*volts)
        # print eeml_readings[0].toeeml().toxml()
        pac.update(eeml_readings)
        try:
            pac.put()
        except:
            logging.debug('pac.put() failure: '+str(sys.exc_info()))
            # print 'pac.put() failure: '+str(sys.exc_info())
    # run = False
    if run:
        time.sleep(10)
